import React from 'react'
import {AutoComplete, message} from 'antd'

const Option = AutoComplete.Option

class UserSearchBox extends React.Component {
  state = {
    dataSource: []
  };

  handleSearch = usernameOrEmail => {
    this.props.searchUserByUsernameOrEmail(usernameOrEmail)
  }

  convertDataSource = () => {
    const {users} = this.props
    const {searchUsers, organizationUsers} = users
    const userIds = organizationUsers.map(user => user.id)

    return searchUsers.map(user => {
      return <Option key={user.id} value={user.username} text={user.username}>
        {user.username}
        ({user.email})
        <span style={{float: 'right'}}>
          {userIds.includes(user.id) ? '已添加' : ''}
      </span>
      </Option>
    })
  }

  isAdded = (organizationUsers,username) => {
    return organizationUsers.map(user=>user.username).includes(username)
  }

  onSelectHandler = username =>{
    const {users, organization} = this.props
    const {organizationUsers, searchUsers} = users
    if(this.isAdded(organizationUsers, username)){
      message.warning('该用户已添加')
      return
    }
    const user = searchUsers.find(user => user.username === username)
    this.props.addOrganizationAdminRole(organization.id,user.id)
  }

  render() {
    const dataSource = this.convertDataSource()

    return (
      <AutoComplete
        size='large'
        style={{width: '100%'}}
        backfill={true}
        dataSource={dataSource}
        onSearch={this.handleSearch}
        onSelect={this.onSelectHandler}
        placeholder='input username or email'
        optionLabelProp='text'

      />

    )
  }
}

export default UserSearchBox
